<template>
  <div id='app'>
    <div ref="editor">

    </div>
  </div>
</template>

<script>
import { upload } from '@/services/course'
import E from 'wangeditor'

export default {
  name: 'TextEditor',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  components: {},
  data () {
    return {
      editor: null,
      // 标记编辑的数据是否加载完毕
      isLoaded: false
    }
  },
  mounted () {
    this.initEditor()
  },
  methods: {
    initEditor () {
      const editor = new E(this.$refs.editor)
      editor.config.onchange = value => {
        this.$emit('input', value)
      }
      // 配置自定义的图片上传功能
      editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
        console.log('上传图片======')
        const fd = new FormData()
        fd.append('file', resultFiles[0])
        const { data } = await upload(fd)
        if (data.code === '000000') {
          // 通过insertImgFn进行数据回显
          insertImgFn(data.data.name)
        }
      }
      editor.create()
      editor.txt.html(this.value)
      this.editor = editor
    }
  },
  watch: {
    value () {
      if (this.isLoaded === false) {
        // 得到了加载的新数据设置给富文本编辑器
        this.editor.txt.html(this.value)
      }
    }
  }
}

</script>
<style scoped>

</style>
